﻿using CommunicationProtocol.dto;
using CommunicationProtocol.dto.command;
using server.filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static CommunicationProtocol.dto.PlantFactory;

namespace server.filter
{
    /**
     * 渲染可购买的植物列表
     */
    public class RenderBuyablePlantListCommand : Command
    {
        public List<StaticPlant> plants { get; }

        public RenderBuyablePlantListCommand(List<StaticPlant> plants) : base(102)
        {
            this.plants = plants;
        }

        public RenderBuyablePlantListCommand(byte[] bytes) : base(102)
        {
            byte plantCount = bytes[0];

            plants = new List<StaticPlant>();

            for (short i = 1; i < plantCount * 5; i += 5)
            {
                short objectId = (short) ((bytes[i] << 8) + bytes[i + 1]);

                short coolingTime = (short) ((bytes[i + 3] << 8) + bytes[i + 4]);

                StaticPlant staticPlant = new StaticPlant(
                    objectId,
                    bytes[i + 2],
                    (byte) (i - 1),
                    0,
                    coolingTime
                );

                plants.Add(staticPlant);
            }
        }

        public override byte[] GetBytes()
        {
            byte[] result = new byte[plants.Count * 5 + 2];

            result[0] = functionCode; // 功能码代表 是可选择的植物列表
            result[1] = (byte) plants.Count; // 可选植物的个数

            for (int i = 0; i < plants.Count; i++)
            {
                int index = i * 5 + 2;
                result[index] = (byte) (plants[i].ObjectId >> 8 & 0xff);
                result[index + 1] = (byte) (plants[i].ObjectId & 0xff);
                result[index + 2] = (byte) (plants[i].ObjectType);
                result[index + 3] = (byte) ((plants[i].coolingTime >> 8) & 0xff);
                result[index + 4] = (byte) ((plants[i].coolingTime) & 0xff);
            }

            return result;
        }
    }
}